//
//  FInputBarHostProxy.m
//  FFoundation
//
//  Created by 新庭 on 2020/2/11.
//

#import "FInputBarHostProxy.h"
#import "FInputBar.h"
#import "FInputBar+Plugin.h"
#import "FInputBarFake.h"
#import "FPluginWrappedData.h"

@interface FInputBarHostProxy () <FInputBarDelegate>

@property (nonatomic, strong) FInputBar *inputBar;
@property (nonatomic, weak) id<FInputBarDelegate> sourceDelegate;

@end

@implementation FInputBarHostProxy

- (instancetype)initWithSource:(id)source {
    if (self = [super initWithSource:source]) {
        self.inputBar = source;
        
        self.sourceDelegate = self.inputBar.delegate;
        self.inputBar.delegate = self;
    }
    return self;
}

#pragma mark - InputBar
- (UIView *)inputBar:(FInputBar *)bar willRenderItem:(FInputBarItem *)item {
    FInputBarFake *fake = (FInputBarFake *)[self fakeForData:(FPluginWrappedData *)item];
    if (fake) {
        return [fake.delegate inputBar:(FInputBar *)fake willRenderItem:item.object];
    } else {
        return [self.sourceDelegate inputBar:bar willRenderItem:item];
    }
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    BOOL rs = YES;
    for (FInputBarFake *fake in self.pluginFakeMap.allValues) {
        if ([fake.delegate respondsToSelector:_cmd]) {
            rs &= [fake.delegate textFieldShouldBeginEditing:textField];
        }
    }
    if ([self.sourceDelegate respondsToSelector:_cmd]) {
        rs &= [self.sourceDelegate textFieldShouldBeginEditing:textField];
    }
    return rs;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    for (FInputBarFake *fake in self.pluginFakeMap.allValues) {
        F_macro_delegate(void, fake.delegate, _cmd, textField);
    }
    F_macro_delegate(void, self.sourceDelegate, _cmd, textField);
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    for (FInputBarFake *fake in self.pluginFakeMap.allValues) {
        F_macro_delegate(void, fake.delegate, _cmd, textField);
    }
    F_macro_delegate(void, self.sourceDelegate, _cmd, textField);
}

@end
